import { equipmentAdd, equipmentDel, equipmentPage, equipmentUpdate } from "@/api/baseData/equipment"
import type { FormInstance, FormRules } from "element-plus"
import { ElMessage } from "element-plus"
import { onMounted, ref } from "vue"
import { lineAll } from '@/api/baseData/productionLine'

interface EquipmentRecord {
  extension?: Record<string, any>
  id: string
  createTime?: string
  updateUser?: string
  updateTime?: string
  createUser?: string
  equipmentCode: string
  equipmentName: string
  equipmentBrand: string
  equipmentType: string
  equipmentSource: string
  equipmentPower: string
  equipmentWeight: string
  leaveCode: string
  description?: string
  activate?: boolean
  isDeleted?: boolean
  clazz?: string
}

interface EquipmentPageResult {
  records: EquipmentRecord[]
  total: number
  size: number
  current: number
  optimizeCountSql: boolean
  searchCount: boolean
  pageSize: number
}

interface ApiResponse<T> {
  code: number
  message: string
  data: T
}

interface PaginationParams {
  current: number
  pageSize: number
}

interface FormData {
  equipmentCode: string
  equipmentName: string
  equipmentBrand: string
  equipmentType: string
  equipmentSource: string
  equipmentPower: string
  equipmentWeight: string
  leaveCode: string
}

// 实现 buildTree 函数用于构建树形结构
export function buildTree(data: any[], idKey: string = 'id', parentKey: string = 'parentId', childrenKey: string = 'children') {
  const result: any[] = []
  const map: Record<string, any> = {}

  // 构建 ID 到节点的映射
  data.forEach(item => {
    map[item[idKey]] = { ...item }
  })

  // 构建树结构
  data.forEach(item => {
    const parentId = item[parentKey]
    if (parentId && map[parentId]) {
      // 如果存在父节点，添加到父节点的 children 中
      if (!map[parentId][childrenKey]) {
        map[parentId][childrenKey] = []
      }
      map[parentId][childrenKey].push(map[item[idKey]])
    } else {
      // 如果不存在父节点，作为根节点
      result.push(map[item[idKey]])
    }
  })

  return result
}

export function useEquipmentData() {
  const searchParam = ref({})
  const isLoading = ref(true)
  const formData = ref<FormData>({
    equipmentCode: "",
    equipmentName: "",
    equipmentBrand: "",
    equipmentType: "",
    equipmentSource: "",
    equipmentPower: "",
    equipmentWeight: "",
    leaveCode: "",
  })
  const ruleFormRef = ref<FormInstance>() // 表单实例引用
  const workOptions = ref<any[]>([])

  const rules = ref<FormRules<FormData>>({
    equipmentCode: [{ required: true, message: "请输入设备编码", trigger: "blur" }],
    equipmentName: [{ required: true, message: "请输入设备名称", trigger: "blur" }],
    equipmentBrand: [{ required: true, message: "请输入设备品牌", trigger: "blur" }],
    equipmentType: [{ required: true, message: "请选择设备类别", trigger: "blur" }],
    equipmentSource: [{ required: true, message: "请输入设备来源", trigger: "blur" }],
    organizationId: [{ required: true, message: "请选择工厂/车间", trigger: "blur" }],
    equipmentPower: [
      { required: true, message: "请输入设备功率(kW)", trigger: "blur" },
      { pattern: /^\d+(\.\d+)?$/, message: "功率只能为数字", trigger: "blur" },
    ],
    equipmentWeight: [
      { required: true, message: "请输入设备重量(kg)", trigger: "blur" },
      { pattern: /^\d+(\.\d+)?$/, message: "重量只能为数字", trigger: "blur" },
    ],
    leaveCode: [{ required: true, message: "请输入出厂编号", trigger: "blur" }],
  })

  const searchFields = ref([
    {
      name: "equipmentCode",
      label: "设备编码",
      component: "input",
      placeholder: "",
      class: "!w-[350px]",
    },
    {
      name: "equipmentName",
      label: "设备名称",
      component: "input",
      placeholder: "",
      class: "!w-[350px]",
    },
    {
      name: "maintenanceDepartmentId",
      label: "维修部门",
      component: "tree-select",
      placeholder: "",
      options: workOptions.value,
      class: "!w-[350px]",
       props: {
        children: 'children',
        label: 'orgName',
        value: 'id',
      },
    },
  ])
  const pageTotal = ref(0)
  const paginatedData = ref<EquipmentRecord[]>([])
  const paginationParams = ref<PaginationParams>({ current: 1, pageSize: 10 })

  const fetchPageData = async (params: any) => {
    isLoading.value = true
    try {
      const response = (await equipmentPage({
        ...params,
        current: paginationParams.value.current,
        pageSize: paginationParams.value.pageSize,
      })) as unknown as ApiResponse<EquipmentPageResult>

      if (response.code === 200) {
        const { records, total } = response.data
        paginatedData.value = records.map((item) => {
          return {
            ...item.extension,
            ...item,
          }
        })
        pageTotal.value = total
      } else {
        ElMessage.error(response.message)
      }
    } catch (error) {
      ElMessage.error("数据获取失败")
    } finally {
      isLoading.value = false // 数据加载完成后设置为 false
    }
  }

  onMounted(() => {
    fetchPageData(searchParam.value)
    
    // 添加获取 workOptions 的代码
    lineAll({current: 1, pageSize: 100000}).then((res) => {
      if (res.code === 200) {
        workOptions.value = buildTree(res.data.records.map((item) => {
          return {
            ...item.extension,
            ...item
          };
        }));
      }
    });
  })

  const handleSearch = () => {
    fetchPageData(searchParam.value)
  }

  const handleSizeChange = (val: number) => {
    paginationParams.value.pageSize = val
    fetchPageData(searchParam.value)
  }

  const handleCurrentChange = (val: number) => {
    paginationParams.value.current = val
    fetchPageData(searchParam.value)
  }

  const addEquipment = async (data: Partial<EquipmentRecord>, callback: () => void) => {
    if (ruleFormRef.value) {
      await ruleFormRef.value.validate(async (valid) => {
        if (valid) {
          const url = data?.id ? equipmentUpdate : equipmentAdd
          const response = (await url(data)) as unknown as ApiResponse<void>
          if (response.code === 200) {
            if (data?.id) {
              ElMessage.success("设备更新成功")
            } else {
              ElMessage.success("设备添加成功")
            }
            fetchPageData(searchParam.value)
            callback()
          } else {
            ElMessage.error(response.message)
          }
        }
      })
    }
  }

  const deleteEquipment = async (id: string) => {
    try {
      const response = (await equipmentDel({ ids: [id] })) as unknown as ApiResponse<void>
      if (response.code === 200) {
        ElMessage.success("删除成功")
        fetchPageData(searchParam.value)
      } else {
        ElMessage.error(response.message)
      }
    } catch (error) {
      ElMessage.error("设备删除失败")
    }
  }

  return {
    searchParam,
    pageTotal,
    paginatedData,
    searchFields,
    isLoading,
    handleSearch,
    handleSizeChange,
    handleCurrentChange,
    addEquipment,
    deleteEquipment,
    paginationParams,
    ruleFormRef,
    rules,
    formData,
    workOptions,
  }
}
